//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user'
//引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由（常量路由）
import { constantRoutes, asyncRoutes, anyRoute } from '@/router/routes'
import router from '@/router'
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

//用于获取当前用户可访问的异步路由
const filterAsyncRoutes = (allAsyncRoutes: any, permissionRoutes: any) => {
  return allAsyncRoutes.filter((item: any) => {
    if (permissionRoutes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, permissionRoutes)
      }
      return true
    }
  })
}

let useUserStore = defineStore('User', {
  //小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识
      menuRoutes: constantRoutes, //仓库存储生成菜单需要的数组（路由）
      userName: '',
      avatar: '',
      buttons: [],
    }
  },
  //异步逻辑的地方
  actions: {
    //用户登录相关的方法
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      //登录请求：成功200->token;失败201->返回错误信息
      if (result.code === 200) {
        //pinia仓库存一下token
        this.token = result.data as string
        //本地持久化存储一份
        SET_TOKEN(result.data as string)
        return 'OK'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息的方法
    async userInfo() {
      let result: userResponseData = await reqUserInfo()
      if (result.code === 200) {
        this.userName = result.data.name
        this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        let userAsyncRoutes = filterAsyncRoutes(
          cloneDeep(asyncRoutes),
          result.data.routes,
        )
        //更新菜单数据
        this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, ...anyRoute]
          // console.log(router.getRoutes())
          //目前路由器管理的只有常量路由,计算完异步路由后和任意路由一起动态追加
          ;[...userAsyncRoutes, ...anyRoute].forEach((item) => {
            router.addRoute(item)
          })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userLogout() {
      let result = await reqLogOut()
      if (result.code === 200) {
        this.token = ''
        this.userName = ''
        this.avatar = ''
        this.buttons = []
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

//对外暴露获取小仓库的方法
export default useUserStore
